package indi.zhifa.study2025.oa.admin.facade.menu.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import indi.zhifa.engine.core.common.utils.DtoEntityUtil;
import indi.zhifa.engine.mpenhance.utils.DbDtoEntityUtil;
import indi.zhifa.study2025.oa.admin.facade.menu.IMenuFacade;
import indi.zhifa.study2025.oa.common.util.ConstantUtil;
import indi.zhifa.study2025.oa.dao.po.GenMenuEntity;
import indi.zhifa.study2025.oa.model.expose.menu.dto.MenuCreateDto;
import indi.zhifa.study2025.oa.model.expose.menu.dto.MenuEditDto;
import indi.zhifa.study2025.oa.model.expose.menu.vo.MenuTreeNode;
import indi.zhifa.study2025.oa.model.expose.menu.vo.MenuVo;
import indi.zhifa.study2025.oa.service.menu.IMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@RequiredArgsConstructor
@Component
public class MenuFacadeImpl implements IMenuFacade {

    final IMenuService menuService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public MenuVo addMenu(Long pParentId, MenuCreateDto pMenuCreateDto) {

        if(!StringUtils.hasText(pMenuCreateDto.getVersionCode())){
            pMenuCreateDto.setVersionCode(ConstantUtil.CURRENT_VERSION);
        }

        GenMenuEntity menuEntity = menuService.checkMin(pParentId);
        GenMenuEntity newMenuEntity = DbDtoEntityUtil.createFromDto(pMenuCreateDto,GenMenuEntity.class);
        newMenuEntity.setParentId(menuEntity.getId());
        newMenuEntity.setCodeCascade(menuEntity.getCodeCascade()+"-"+newMenuEntity.getCode());
        newMenuEntity.setAppCode(menuEntity.getAppCode());
        newMenuEntity.setAppId(menuEntity.getAppId());


        newMenuEntity = menuService.create(newMenuEntity);
        MenuVo menuVo = DtoEntityUtil.trans(newMenuEntity,MenuVo.class);
        return menuVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public MenuVo edit(Long pId, MenuEditDto pMenuEditDto) {
        GenMenuEntity menuEntity = menuService.edit(pId, pMenuEditDto);
        MenuVo menuVo = DtoEntityUtil.trans(menuEntity,MenuVo.class);
        return menuVo;
    }

    @Override
    public MenuVo delete(Long pId) {
        GenMenuEntity delEntity = menuService.delete(pId);
        MenuVo menuVo = DtoEntityUtil.trans(delEntity,MenuVo.class);
        return menuVo;
    }

    @Override
    public MenuTreeNode getTreeNode(Long pId) {
        return menuService.getTree(pId);
    }

    @Override
    public MenuVo info(Long pId) {
        GenMenuEntity menuEntity = menuService.check(pId);
        MenuVo menuVo = DtoEntityUtil.trans(menuEntity,MenuVo.class);
        return menuVo;
    }
}
